package com.css.fxfzcpxx.modules.getTemplate.controller;

import com.css.fxfzcpxx.modules.getTemplate.entity.FileName;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

@RestController
@RequestMapping("/template")
@Slf4j
@Api(tags ="模板下载")
public class TemplateController {

    @PostMapping(value = "/download", produces = "text/html;charset=UTF-8")
    public void downloadExcel1(@RequestBody FileName fileName, HttpServletResponse response) {
        log.info("入参: 模板名全称", fileName.getFileName());
        try {
            //请求头的模板名为中文
            String file_name = URLEncoder.encode(fileName.getFileName(), "UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;fileName=" + file_name);
            response.setContentType("application/x-download");
            //获取文件的路径
            //String path = getClass().getResource("/template/" + fileName.getFileName()).getPath();
            String path = "/usr/zhaoshuai/cpxx/template/"+fileName.getFileName();
            //路径名转换中文
            String filePath = URLDecoder.decode(path, "utf-8");
            FileInputStream inputStream = new FileInputStream(filePath);
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[65536];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            log.info(fileName.getFileName() + ": 模板下载完成");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(fileName.getFileName() + ":" + e);
        }
    }
}
